package com.wasion.core.util;

public class CRC16 {
    // our crc agorithm is sample, just add all bytes together, and get the last
    // bytes.
    public static String calc(byte[] bytes) {
	int a = 0;
	int b = 0;

	a = bytes[0];

	for (int count = 1; count < bytes.length; count++) {
	    b = bytes[count];
	    a = a + b;
	}

	String crc = Integer.toHexString((0x00FF & a)); // 0xFFFF 单字节 //0x00FF
							// 去掉高位

	if (crc.length() == 1)
	    return crc = "0" + crc; // 有可能 CRC 出来只有1位。必须加"0" 在高位。
	else
	    return crc;
    }

    public int value;

    public CRC16() {
	value = 0;
    }

    public int getValue() {
	return value;
    }

    /** reset CRC value to 0 */
    public void reset() {
	value = 0;
    }

    /*
     * //test program public static void main(String[] args) { CRC16 crc16 = new
     * CRC16();
     * 
     * byte[] b = new byte[] { // (byte) 0xF0,(byte)0xF0,(byte)0xF0,(byte)0x72
     * (byte) 0x7E, (byte) 0x0A, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte)
     * 0xAA, (byte) 0x49, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00,
     * (byte) 0xE0};
     * 
     * byte[] a = new byte[] { // (byte) 7E 0A 11 11 11 30 49 01 00 00 00 04
     * (byte) 0x7E, (byte) 0x0A, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte)
     * 0x30, (byte) 0x49, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00,
     * (byte) 0x04};
     * 
     * 
     * System.out.println(crc16.calc(a));
     * System.out.println(Integer.toHexString(crc16.getValue()));
     * System.out.println(Integer.toHexString(a.length)); }
     */
}
